<script>
  function CutePromise(executor) {
    this.status = 'pending';
    this.value = null;    //resolve 结果
    this.reason = null;   //错误的原因
    this.onFulfilledCbs = [];   // 数组
    this.onRejectedCbs = [];    // 
    // 怎么知道 调用了：
    // resolve  -> fulfilled
    // reject   -> rejected
    let self = this;
    function resolve(value) {
      console.log('resolve called');
      self.status = 'fulfilled';
      self.value = value;
      // console.log('val', value);
      // 让 then onFulfilled 回调调用
      for (let fn of self.onFulfilledCbs) {
        fn(value);
      }
    }
    function reject(reason) {
      self.status = 'rejected';
      self.reason = reason;
      // // 让 then onRejected 回调调用
      for (let fn of self.onRejectedCbs) {
        fn(reason);
      }
    }
    executor(resolve, reject);
  }
  CutePromise.prototype.then = function (onFulfilled, onRejected) {
    let self = this;
    if (self.status === 'fulfilled') {
      onFulfilled(self.value);
    } else if (self.status === 'rejected') {
      onRejected(self.reason);
    } else if (self.status === 'pending') {
      // onFulfilled onRejected 先等着 等着 resolve() reject()
      // 才会执行
      self.onFulfilledCbs.push(onFulfilled);
      self.onRejectedCbs.push(onRejected);
    }
  }
  new CutePromise((resolve, reject) => {
    // resolve(6666);
    // 成功时候的值 通过 resolve 传给
    // reject('err')
    setTimeout(() => {
      // 2000 => fulfilled
      resolve(6666);
    }, 2000)
  })
    .then((val) => {
      console.log('then cb called');
      console.log(val);
    })
  // .then(() => {
  //   console.log('2th then')
  // })
</script>